/**
  @Author: 王炜皓
  @Date: 2023-06-07 18:35:58
  @LastEditTime: 2023-06-07 19:36:27
  @LastEditors: 王炜皓
  @Description: 截图
  @FilePath: \cesium-tool\src\views\test\extend\captureScreen\captureScreen.js
 **/
const Cesium = window.Cesium;
/**
 * @description： 将地图canvas及上面的entity转换为bolb对象
 * @param： viewer地图对象
 */
export function captureScreenshot(viewer) {
//   const { when } = Cesium;
//   const deferred = when.defer();
//   const scene = viewer.scene;
//   let removeCallback = scene.postRender.addEventListener(function () {
//     removeCallback();
//     try {
//       const cesiumCanvas = viewer.scene.canvas;
 
//       // If we're using the splitter, draw the split position as a vertical white line.
//       let canvas = cesiumCanvas;
//       canvas.toBlob(function (blod) {
//         deferred.resolve(blod);
//       }, "image/png");
//       // deferred.resolve(canvas.toDataURL("image/png"));
//     } catch (e) {
//       deferred.reject(e);
//     }
//   }, this);
//   scene.render(viewer.clock.currentTime);
//   return deferred.promise;
const scene = viewer.scene;
return new Promise((resolve, reject) => {
    try {
      const cesiumCanvas = viewer.scene.canvas;
      const deferred = scene.postRender.addEventListener(function () {
        deferred();
        try {
          cesiumCanvas.toBlob(function (blob) {
            resolve(blob);
          }, "image/png");
        } catch (error) {
          reject(error);
        }
      }, this);
      scene.render(viewer.clock.currentTime);
    } catch (error) {
      reject(error);
    }
  });
}
/**
 * @description： 将bolb对象导出为图片
 * @param： blob对象
 * @param： filename文件名
 */
export function saveAs(blob, filename) {
  if (blob === null) {
    return;
  }
  if (window.navigator.msSaveOrOpenBlob) {
    navigator.msSaveBlob(blob, filename);
  } else {
    const target = document.createElement("a");
    const body = document.querySelector("body");
    target.href = window.URL.createObjectURL(blob);
    target.download = filename;
    target.style.display = "none";
    body.appendChild(target);
    target.click();
    body.removeChild(target);
    window.URL.revokeObjectURL(target.href);
  }
}
/**
 * 将Blob对象转换为base64
 * @param {*} blob Blob对象
 * @returns base64值
 */
export function blobToBase64(blob) {
  return new Promise((resolve, reject) => {
    const fileReader = new FileReader();
    fileReader.onload = (e) => {
      resolve(e.target.result);
    };
    // readAsDataURL
    fileReader.readAsDataURL(blob);
    fileReader.onerror = () => {
      reject(new Error("blobToBase64 error"));
    };
  });
}